package org.jeecg.common.util.ali;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.google.api.client.util.Maps;
import com.google.common.collect.Lists;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import me.kagura.JSONQuery;
import me.kagura.JsonResult;

public class WuliuUtil {
	private static final String host = "https://kdwlcxf.market.alicloudapi.com";// 【1】请求地址 支持http 和 https 及 WEBSOCKET
    private static final String path = "/kdwlcx";// 【2】后缀
    private static final String appcode = "3be399f33fe2400cafab96121ca2ae46"; // 【3】开通服务后 买家中心-查看AppCode
	
	/**
	 * @Description 
	 * @param no
	 * @param type
	 * @return
	 * Create at: 2020-10-17 16:26:47
	 * @author: duanyong
	 * Revision:
	 *    2020-10-17 16:26:47 - first revision by duanyong
	 *        
	 */
	public static List<Map<String, String>> getWuliu(String no, String type) {
		String urlSend = host + path + "?no=" + no; // 【5】拼接请求链接
		if(StringUtils.isNotBlank(type)) {
			urlSend += "&type=" + type;
		}
		try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);// 格式Authorization:APPCODE
                                                                                        // (中间是英文空格)
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                System.out.println("正常请求计费(其他均不计费)");
                System.out.println("获取返回的json:");
                System.out.print(json);
                List<Map<String, String>> resultList = Lists.newArrayList();
                JsonResult jsonResult = JSONQuery.select(json, "result > list");
                JsonArray jsonArray = jsonResult.getAsJsonArray();
                for (int i = 0; i < jsonArray.size(); i++) {
                	Map<String, String> map = Maps.newLinkedHashMap();
                	JsonElement element = jsonArray.get(i);
                	JsonObject jsonObject = element.getAsJsonObject();
                	String time = jsonObject.get("time").getAsString();
                	String status = jsonObject.get("status").getAsString();
                	map.put("time", time);
                	map.put("status", status);
                	resultList.add(map);
				}
                return resultList;
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    System.out.println("AppCode错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    System.out.println("请求的 Method、Path 或者环境错误");
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    System.out.println("参数错误");
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    System.out.println("服务未被授权（或URL和Path不正确）");
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    System.out.println("套餐包次数用完 ");
                } else {
                    System.out.println("参数名错误 或 其他错误");
                    System.out.println(error);
                }
            }

        } catch (MalformedURLException e) {
            System.out.println("URL格式错误");
        } catch (UnknownHostException e) {
            System.out.println("URL地址错误");
        } catch (Exception e) {
            // 打开注释查看详细报错异常信息
             e.printStackTrace();
        }
		
		return null;
	}
    public static void main(String[] args) {
        String no = "780098068058"; // 【4】请求参数，详见文档描述
        String type = "ZTO"; //  【4】请求参数，不知道可不填 95%能自动识别
        getWuliu(no, type);
    }

    /*
     * 读取返回结果
     */
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }
}